package com.company.arrays;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

public class RemoveDuplicates {
    public int removeDuplicates(int[] nums) {
       return bySet(nums);

    }

    private int bySet(int[] nums){
        List<Integer> values = new ArrayList<>();
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            int v = nums[i];
            if (values.size() ==0) {
                values.add(v);
                count++;
                continue;
            }
            Integer lastValue = values.get(values.size()-1);
            if (v != lastValue) {
                count = 1;
            }
            if (count==2) {
                continue;
            }
            values.add(v);
            count++;
        }

        for (int i = 0; i < values.size(); i++) {
            nums[i] = values.get(i);
        }

        return values.size();
    }


    private int byLoop(int[] nums){
        int currentValue;
        int size = nums.length;
        for (int i = 0; i < nums.length;) {
            currentValue = nums[i];
            int totalCount = totalCountOfValue(nums, currentValue,size);
            if (totalCount>2) {
                int extSize = totalCount -2;
                i+=extSize;
                size-=extSize;
                int secondIndex = getSecondIndex(nums, currentValue);
                moveForvard(nums,secondIndex,extSize);
            }else {
                i+=totalCount;
            }
        }
        return size;
    }

    private int getSecondIndex(int[] nums,int value){
        int index = 0;
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i]==value) {
                index = i;
                count++;
                if (count == 2) {
                    break;
                }
            }
        }
        return index;
    }

    private int totalCountOfValue(int[] nums,int value,int size){
        int count = 0;
        for (int i = 0; i < size; i++) {
            if (nums[i] == value) {
                count++;
            }
        }

        return count;
    }
    private void moveForvard(int[] nums, int offset,int step) {
        for (int i = offset; i < nums.length - step; i++) {
            nums[i] = nums[i + step];
        }
    }

}
